package com.hailiang.ing;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ProvinceServlet extends HttpServlet {
    private Statement statement;
    private Connection conn;
    private ResultSet resultSet;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            resp.setContentType("application/json;charset=utf-8");
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo1", "root", "root");
            statement = conn.createStatement();
            resultSet = statement.executeQuery("select * from province");
            List<ProvinceBean> provinces = new ArrayList();
            while (resultSet.next()) {
                ProvinceBean province = new ProvinceBean();

                province.setId(resultSet.getInt("id"));
                province.setName(resultSet.getString("name"));
                provinces.add(province);
            }
            String s = JSON.toJSONString(provinces);
            resp.getWriter().write(s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
                statement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}